<template>
	<view class="">
		<button open-type="chooseAvatar" @chooseavatar="onChooseAavtar">
			<image :src="userInfo.avatar" mode=""></image>
		</button>
		<input type="nickname" class="updateInfoInput" v-model="userInfo.nickName" />
		<button @click="updateInfo">保存</button>

		<view class="pciker-item">
			<picker @change="bindPickerChange" :value="index" :range="array">
				<view class="uni-input">{{array[index]}}</view>
			</picker>
		</view>
		<view class="pciker-item">
			<picker mode="time" :value="time" start="09:01" end="21:01" @change="bindTimeChange">
				<view class="uni-input">{{time}}</view>
			</picker>
		</view>
		<view class="pciker-item">
			<picker mode="date" :value="date" start="1998-01-01" end="2025-07-08" @change="bindDateChange">
				<view class="uni-input">{{date}}</view>
			</picker>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from 'vue';
	import {
		useUserStore
	} from '../../store/user';
	import {
		updateInfoApi
	} from '../../api/mine';
	const userStore = useUserStore();

	const userInfo = ref({
		nickName: '',
		avatar: ''
	});
	const index = ref(0);
	const array = ref(['四川', '贵州', '重庆', '云南']);
	const time = ref('10:10');
	const date = ref('1998-05-09');
	watch(() => userStore.userInfo, () => {
		userInfo.value = {
			...userStore.userInfo
		};
	}, {
		immediate: true
	});

	function bindTimeChange(event) {
		time.value = event.detail.value;
	}

	function bindPickerChange(event) {
		index.value = event.detail.value;
	}
	
	function bindDateChange (event){
		date.value = event.detail.value;
	}

	function onChooseAavtar(event) {
		userInfo.value.avatar = event.detail.avatarUrl;
		uni.uploadFile({
			url: 'http://nocat.life:3017/images/upload',
			filePath: userInfo.value.avatar,
			name: 'file',
		}).then(res => {
			const temp = JSON.parse(res.data);
			if (temp.code == 200) {
				userInfo.value.avatar = temp.data;
			}
		})
	}

	function updateInfo() {
		updateInfoApi({
			...userStore.userInfo,
			...userInfo.value
		}).then(res => {
			if (res.code == 200) {
				userStore.getUserInfoAction();
				uni.navigateBack({
					delta: 1
				})
			}
		})
	}
</script>

<style scoped>
	.updateInfoInput {
		border: 1px solid;
	}

	.pciker-item {
		text-align: center;
		height: 30rpx;
		margin: 20rpx 0;
	}
</style>